package cn.relx.service.controller;

import cn.relx.basic.annotation.PreAuthorize;
import cn.relx.service.service.IProductService;
import cn.relx.service.domain.Product;
import cn.relx.service.query.ProductQuery;
import cn.relx.basic.util.AjaxResult;
import cn.relx.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    public IProductService productService;


    /**
     * 保存和修改公用的
     * @param product  传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Product product){
        try {
            if( product.getId()!=null)
                productService.update(product);
            else
                productService.add(product);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("保存对象失败！"+e.getMessage());
        }
    }
    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value="/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            productService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
        e.printStackTrace();
            return AjaxResult.me().setMsg("删除对象失败！"+e.getMessage());
        }
    }
	
    //获取用户
    @GetMapping("/{id}")
    public Product get(@PathVariable("id")Long id)
    {
        return productService.findById(id);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @GetMapping()
    public List<Product> list(){

        return productService.findAll();
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping("/list")
    public PageList<Product> json(@RequestBody ProductQuery query)
    {
        return productService.queryByPage(query);
    }

    /**
     * 上架
     * @param ids
     * @return
     */
    @PostMapping("/onsale") // @RequestBody：获取请求体中的参数
    public AjaxResult onsale(@RequestBody List<Long> ids)
    {
        productService.onsale(ids);
        return AjaxResult.me().success();
    }


    /**
     * 下架
     * @param ids
     * @return
     */
    @PostMapping("/offsale") // @RequestBody：获取请求体中的参数
    public AjaxResult offsale(@RequestBody List<Long> ids)
    {
        productService.offsale(ids);
        return AjaxResult.me().success();
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping("/batchDel")
    public AjaxResult batchDel(@RequestBody List<Long> ids){
        productService.batchDel(ids);
        return AjaxResult.me().success();
    }

    @GetMapping("/getPetDetail/{id}")
    public Product getPetDetail(@PathVariable("id")Long id){
        return productService.getPetDetail(id);
    }
}
